package com.itheima.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.itheima.common.TokenHolder;
import com.itheima.entity.AddressBook;
import com.itheima.mapper.AddressMapper;
import com.itheima.service.AddressBookService;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
 *地址模块业务层实现类
 * @author msi
 * @date 2022/5/17
 * @version 1.0
 */
@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Resource
    private AddressMapper mapper;

    @Override
    public List<AddressBook> getList() {

        return mapper.getList();

    }

    @Override
    public AddressBook insert(AddressBook addressBook) {

        Snowflake snowflake = IdUtil.getSnowflake();
        String id = snowflake.nextIdStr();
        addressBook.setId(id);
        String currentId = TokenHolder.getCurrentId();
        addressBook.setUserId(currentId);

        addressBook.setCreateTime(new Date());
        addressBook.setCreateUser(addressBook.getUserId());
        addressBook.setUpdateUser(addressBook.getUserId());
        addressBook.setUpdateTime(new Date());
         mapper.insertAddress(addressBook);

        return addressBook;
    }

    @Override
    public Boolean update(AddressBook addressBook) {
        addressBook.setUpdateTime(new Date());
        addressBook.setUpdateUser(TokenHolder.getCurrentId());
        int i = mapper.update(addressBook);

        return i > 0;
    }

    @Override
    public AddressBook getAddressById(String id) {

        return mapper.getOneAddress(id);
    }

    @Override
    public Boolean delete(String ids) {
        int i = mapper.delete(ids);

        return i > 0;
    }

    @Override
    public AddressBook getDefaultAddress() {

        return mapper.getDefaultAddress();
    }

    @Override
    public Boolean updateDefault(AddressBook addressBook) {
        String id = addressBook.getId();
        AddressBook defaultAddress = mapper.getDefaultAddress();
        if (defaultAddress!=null){
            mapper.updateDefaultFalse(defaultAddress.getId());
        }
       int i= mapper.updateDefault(id);

        return i>0;
    }
}
